﻿using System;
using System.Net.Http;
using System.Threading.Tasks;

using IdentityModel.Client;

using Newtonsoft.Json.Linq;

namespace ClientCredentialsConsoleApp
{
    class Program
    {
        static async Task Main(string[] args)
        {
            //discovery endpoint - 发现终结点
            HttpClient client = new HttpClient();
            DiscoveryDocumentResponse disco =
                await client.GetDiscoveryDocumentAsync("http://localhost:5000");
            if (disco.IsError)
            {
                Console.WriteLine($"[DiscoveryDocumentResponse Error]: {disco.Error}");
                return;
            }

            //request access token - 请求访问令牌
            TokenResponse tokenResponse = await client.RequestClientCredentialsTokenAsync(
                new ClientCredentialsTokenRequest
                {
                    Address = disco.TokenEndpoint,
                    ClientId = "client",
                    ClientSecret = "secret",
                    Scope = "api1"
                });
            if (tokenResponse.IsError)
            {
                Console.WriteLine($"[TokenResponse Error]: {tokenResponse.Error}");
                return;
            }
            else
            {
                Console.WriteLine("");
                Console.WriteLine($"Access Token: {tokenResponse.AccessToken}");
            }

            //call API Resource - 访问API资源
            HttpClient apiClient = new HttpClient();
            apiClient.SetBearerToken(tokenResponse.AccessToken);
            HttpResponseMessage response = await apiClient.GetAsync("http://localhost:6000/weatherforecast");
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine($"API Request Error, StatusCode is : {response.StatusCode}");
            }
            else
            {
                string content = await response.Content.ReadAsStringAsync();
                Console.WriteLine("");
                Console.WriteLine($"Result: {JArray.Parse(content)}");
            }

            Console.ReadKey();
        }
    }
}
